package com.junko.dao.back;

import com.junko.core.base.BaseDao;
import com.junko.model.back.Module;
import com.junko.model.back.System;
import com.junko.model.back.ZtreeNode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository
public class ModuleDao extends BaseDao<Module> {

    @Autowired
    private SystemDao systemDao;

    public List<Module> findTopParentsBySystemId(Integer systemId){
        return getSqlSession().selectList(this.getNameSpace() + ".findTopParentsBySystemId",systemId);
    }
    public List<Module> findByParentId(Integer parentId){
        return getSqlSession().selectList(this.getNameSpace() + ".findByParentId",parentId);
    }

    /**
     * 获取子节点数据
     * @param parentId
     * @return
     */
    public List<ZtreeNode> childNodeData(String systemId, Integer parentId){
        List<Module> list = new ArrayList<>();
        if(parentId!=null){
            list = getSqlSession().selectList(this.getNameSpace()+".findChildByParentId",parentId);
        }else{
            if(StringUtils.isNotBlank(systemId)){
                list = getSqlSession().selectList(this.getNameSpace()+".findRootBySystemId",systemId);
            }else{
                List<System> systemList = systemDao.findAll();
                for (System system : systemList) {
                    list.addAll(getSqlSession().selectList(this.getNameSpace()+".findRootBySystemId",system.getId()));
                }
            }
        }
        List<ZtreeNode> nodeList = new ArrayList<ZtreeNode>();
        ZtreeNode node;
        for (Module menu : list) {
            node = new ZtreeNode();
            node.setId(menu.getId()+"");
            node.setName(menu.getName());
            node.setIsParent(true);
            nodeList.add(node);
        }
        return nodeList;
    }
}